<template>
  <scroll 
    class="listview" 
    :data="data" 
    ref="listView"
    :listenScroll = "listenScroll"
    :probeType = "probeType"
    @scroll = "scroll"
  >
    <ul>
      <li
        v-for="(group, index) in data"
        class="list-group"
        :key="index"
        ref="listGroup"
      >
        <h2 class="list-group-title">{{ group.title }}</h2>
        <ul>
          <li
            v-for="(item, index) in group.items"
            class="list-group-item"
            :key="index"
            @click="selectedItem(item)"
          >
            <img v-lazy="item.avatar" class="avatar" />
            <span class="name">{{ item.name }}</span>
          </li>
        </ul>
      </li>
    </ul>
    <div
      class="list-shortcut"
      @touchstart="onShortcutTouchStart"
      @touchmove.stop.prevent="onShortcutTouchMove"
    >
      <ul ref="shortcutList">
        <li
          v-for="(item, index) in shortcutList"
          class="item"
          :key="index"
          :data-index="index"
          :class="{'current': currentIndex === index}"
        >
          {{ item }}
        </li>
      </ul>
    </div>
    <div class="list-fixed" ref="fixed" v-show="fixedTitle">
      <h1 class="fixed-title">{{ fixedTitle }}</h1>
    </div>
  </scroll>
</template>

<script>
import Scroll from "base/scroll/scroll"
import { getData } from "common/js/dom"

const ANCHOR_HEIGHT = 18

export default {
  created() {
    this.touch = {},
    this.listenScroll = true,
    this.probeType = 3
  },
  data() {
    return {
      scrollY: -1,
      currentIndex: 0,
      roll_diff: -1    // 滚动时候的差值
    }
  },
  props: {
    data: {
      type: Array,
      default: [],
    },
  },
  components: {
    Scroll
  },
  computed: {
    shortcutList() {
      return this.data.map((group) => {
        return group.title.substr(0, 1)
      })
    },
    fixedTitle() {
      if (this.scrollY > 0) {
        return ''
      }
      return this.data[this.currentIndex] ? this.data[this.currentIndex].title : ''
    }
  },
  methods: {
    refresh() {
      this.$refs.listView.refresh()
    },
    onShortcutTouchStart(e) {
      // anchorIndex为右侧列表被点击到的字母的索引值
      let anchorIndex = getData(e.target, "index")

      // 首次触摸右侧列表记录的pageY值
      let firstTouch = e.touches[0];
      this.touch.y1 = firstTouch.pageY

      // 记录一开始点击的是哪个字母的索引
      this.touch.anchorIndex = anchorIndex

      this._scrollTo(this.touch.anchorIndex)

    },
    onShortcutTouchMove(e) {
      let lastTouch = e.touches[0]

      this.touch.y2 = lastTouch.pageY

      // 计算最后一次点击与上一次点击的偏移
      let diff = Math.floor( ( this.touch.y2 - this.touch.y1 ) / ANCHOR_HEIGHT )

      // 得到触摸移动时的字母索引
      let anchorIndex = parseInt(this.touch.anchorIndex) + diff
      this._scrollTo(anchorIndex)
    },

    scroll(pos) {
      this.scrollY = pos.y
    },

    // 向父元素派发歌手被点击事件，跳转至歌手详细页面
    selectedItem(item) {
      this.$emit('selectedItem', item)
    },

    _scrollTo(anchorIndex) {
      // touchMove事件移动到热点以上，anchorIndex会变成负值，要保持anchorIndex为0
      // 同样移动到z以下也是同样情况处理
      if (anchorIndex < 0) {
        anchorIndex = 0
      } else if (anchorIndex > this.listHeight - 2) {
        anchorIndex = this.listHeight - 2
      }

      // 因为touchStart事件是在父元素上执行，所以点击热点以上的区域anchorindex为null，当为null时return
      if (!anchorIndex && anchorIndex !== 0) {
        return
      }
      this.scrollY = -this.listHeight[anchorIndex] -1
      // scrollToElement第二个参数为0的含义是是否加入缓动动画效果
      this.$refs.listView.scrollToElement(this.$refs.listGroup[anchorIndex], 0)
    },

    _calculataHeight() {
      // 每个list的高度的集合
      this.listHeight = []

      // 拿到全部的list
      const list = this.$refs.listGroup

      // 定义初始高度
      let height = 0

      this.listHeight.push(height)

      for (let i = 0; i < list.length; i++) {
        let item = list[i]

        // 初始高度加元素客户区的大小，指的是元素内容及其边框所占据的大小
        height += item.clientHeight
        this.listHeight.push(height)
      }
    }
  },
  watch: {
    data() {
      setTimeout(() => {
        this._calculataHeight()
      }, 20)
    },
    
    scrollY(newY) {
      const listHeight = this.listHeight
      // console.log(newY)
      // 当滚动到顶部以上时，currentIndex都为0
      if (newY > 0) {
        this.currentIndex = 0
        return
      }

      // 在中间进行滚动
      for (let i = 0; i < listHeight.length - 1; i++) {
        let height1 = listHeight[i]
        let height2 = listHeight[i + 1]
        
        
        // 判断当前滚动的Y值落在哪个位置
        if (-newY >= height1 && -newY < height2) {
          this.roll_diff = height2 + newY
          this.currentIndex = i
          return
        } 
      }

      // 当它滚动到底部，且-newY大于最后一个元素的上限
      this.currentIndex = listHeight.length - 2
      
    },

    // 实时计算滚动时的差值
    roll_diff(newVal) {
      let fixedTop = (newVal > 0 && newVal < 30) ? newVal - 30 : 0
      
      // 如果不在30的区间内则返回
      if (this.fixedTop === fixedTop) {
        return
      }
      this.fixedTop = fixedTop
      this.$refs.fixed.style.transform = `translate3d(0,${fixedTop}px,0)`
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~common/stylus/variable';

.listview {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: $color-background;

  .list-group {
    padding-bottom: 30px;

    .list-group-title {
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }

    .list-group-item {
      display: flex;
      align-items: center;
      padding: 20px 0 0 30px;

      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }

      .name {
        margin-left: 20px;
        color: $color-text-l;
        font-size: $font-size-medium;
      }
    }
  }

  .list-shortcut {
    position: absolute;
    z-index: 30;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    padding: 20px 0;
    border-radius: 10px;
    text-align: center;
    background: $color-background-d;
    font-family: Helvetica;

    .item {
      padding: 3px;
      line-height: 1;
      color: $color-text-l;
      font-size: $font-size-small;

      &.current {
        color: $color-theme;
      }
    }
  }

  .list-fixed {
    position: absolute;
    top: -1px;
    left: 0;
    width: 100%;

    .fixed-title {
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }
  }

  .loading-container {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>